package com.modbus;

import com.modbus.config.ModbusConfig;
import com.modbus.config.ModbusMasterConfig;
import com.modbus.entity.exception.ConnectionException;
import com.modbus.handler.exmple.ModbusRequestHandlerExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author heyayun
 * @description TODO
 * @date 2021/3/23 14:40
 */
@Slf4j
@Component
public class ModbusMasterServer {
    @Autowired
    private ModbusConfig modbusConfig;
    @Autowired
    private ModbusRequestHandlerExample modbusRequestHandlerExample;
    @Bean
    public ModbusServer start() {
        ModbusMasterConfig config = ModbusMasterConfig
                .builder(modbusConfig.getAddress())
                .setPort(modbusConfig.getPort())
                .build();
        ModbusServer modbusServer = new ModbusServer(config);
        try {
            modbusServer.setup(modbusRequestHandlerExample);
            log.info("Modbus started on port(s): {}", modbusConfig.getPort());
            log.info("Modbus Server Start !!!!!!");
            return modbusServer;
        } catch (ConnectionException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
}
